package com.learn.security.filter;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.alibaba.fastjson2.JSON;
import com.learn.security.config.props.JwtProperties;
import com.learn.security.pojo.vo.LoginUser;
import com.learn.util.JwtUtil;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

// @Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String uri = request.getRequestURI();
        if(uri.equals("/user/login") || uri.equals("/captcha")){
            // 直接放行
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader("Authorization");
        if(!StringUtils.hasLength(token)){
            throw new RuntimeException("无效的token");
        }
        String info = JwtUtil.getInfo(token);
        if(!StringUtils.hasLength(info)){
            throw new RuntimeException("无效的token");
        }
        LoginUser loginUser = JSON.parseObject(info, LoginUser.class);
        if(loginUser == null){
            throw new RuntimeException("无效的token");
        }
        if(!JwtUtil.checkSign(token, jwtProperties.getSecret())){
            // 将用户信息存入ThreadLocal
            throw new RuntimeException("无效的token");
        }
        UsernamePasswordAuthenticationToken authenticationToken = 
            new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
    
}